import { Injectable, NotFoundException } from '@nestjs/common';
import { CreateVideoDto } from './dto/create-video.dto';
import { UpdateVideoDto } from './dto/update-video.dto';
import { Repository, In } from 'typeorm';
import { InjectRepository } from '@nestjs/typeorm';
import { Video } from './entities/video.entity';
import { FileUtil } from '../common/file';

@Injectable()
export class VideoService {

  constructor(
    @InjectRepository(Video)
    private readonly videoRepository: Repository<Video>,
  ) {}

  async create(createVideoDto: CreateVideoDto) {
    const video = this.videoRepository.create(createVideoDto);
    const insertRes =  await this.videoRepository.insert(video);
    return insertRes.raw;
  }

  async createForScript(createVideoDto: CreateVideoDto) {
    const video = this.videoRepository.create(createVideoDto);
    const insertRes =  await this.videoRepository.insert(video);
    return insertRes.raw[0].id;;
  }

  async findAll(): Promise<Video[]> {
    return this.videoRepository.find();
  }

  async findOne(id: string): Promise<Video> {
    return this.videoRepository.findOne({ where: { id: id } });
  }

  async findByIds(ids: string[]): Promise<Video[]> {
    return this.videoRepository.find({
      where: {
        id: In(ids), // 使用TypeORM的In操作符
      },
    });
  }

  async update(id: string, updateVideoDto: UpdateVideoDto) {
    const oldItem = await this.videoRepository.findOne({ where: { id } });

    if (!oldItem) {
      throw new NotFoundException('该修改对象不存在');
    }

    // Object.assign是可行的，这里显示使用了TypeORM的merge方法作为替代示例
    const updatedVideo = this.videoRepository.merge(oldItem, updateVideoDto);

    await this.videoRepository.save(updatedVideo);

    // 返回更新后的实体或其他有用的信息
    return updatedVideo;
  }

  async remove(id: string) {
    try {
      const oldVideo = await this.videoRepository.findOne({
        where: { id: id },
      });
      const result = await this.videoRepository.delete({ id: id });

      if (result.affected && result.affected > 0) {
        return `成功删除 ${result.affected} 条记录`;
      } else {
        return `未找到匹配的记录，没有进行删除操作`;
      }
    } catch (err) {
      console.error('删除记录失败', err);
      throw '删除记录失败';
    }
  }
}
